import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
const _import = require('./router/_import_' + process.env.NODE_ENV) // 获取组件的方法
import Layout from '@/layout' // Layout 是架构组件，不在后台返回，在文件里单独引入
import { Base64 } from 'js-base64'
import defaultSettings from '@/settings'
import { generateUUID, postMessage, receivedMessage } from '@/utils/index'
const whiteList = ['/login', '/bigScreen', '/bigScreenDesign', '/testDeviceChoose'] // no redirect whitelist

var getRouter // 用来获取后台拿到的路由
// 判断是否已经注册过动态路由的标志
var isDynamicRoutesRegistered = false

router.beforeEach(async (to, from, next) => {
  NProgress.configure({ showSpinner: false, parent: 'body' }) // NProgress Configuration
  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken || defaultSettings.isWPF || defaultSettings.isCEF) {
    if (defaultSettings.isWPF || defaultSettings.isCEF) {
      try {
        if (to.path === '/login') {
          // if is logged in, redirect to the home page
          next({ path: '/' })
          NProgress.done()
        } else {
          // 判断是否已经注册过动态路由，避免重复注册
          if (!isDynamicRoutesRegistered) {
            let menuData = {}
            let flag = false

            const getInfoRequestId = generateUUID()
            let params = {
              RequestUrl: process.env.VUE_APP_URL + '/login/getInfo',
              RequestMethod: 'POST',
              Headers: {
                contentType: 'application/json'
              },
              QueryParameter: {},
              RequestBody: {},
              WebInfo: {
                requestId: getInfoRequestId
              }
            }

            setTimeout(() => {
              postMessage(params)
              receivedMessage((result) => {
                let e = defaultSettings.isWPF ? result : { data: JSON.parse(result) }
                if (e.data?.webInfo?.requestId === getInfoRequestId) {
                  menuData = e.data.response.data
                  flag = true
                }
              })
            }, 500)

            const setMenus = (data) => {
              if (!getRouter) {
                let timer = setInterval(() => {
                  if (flag) {
                    getRouter = menuData.menus
                    store.dispatch('user/menusSetting', menuData)
                    saveObjArr('dpagmRouter', getRouter) // 存储路由到localStorage
                    // eslint-disable-next-line require-atomic-updates
                    isDynamicRoutesRegistered = true
                    clearInterval(timer)
                    routerGo(to, next) // 执行路由跳转方法
                  }
                }, 500)
              } else {
                console.log('next')
                next()
              }
            }
            setMenus()
          } else {
            console.log('next')
            next()
          }
        }
      } catch (error) {
        next({ path: '/' })
        NProgress.done()
        // remove token and go to login page to re-login
        // await store.dispatch('user/resetToken')
        // Message.error(error || 'Has Error')
        // next(`/login?redirect=${to.path}`)
        // NProgress.done()
      }
    } else {
      if (to.path === '/login') {
        // if is logged in, redirect to the home page
        next({ path: '/' })
        NProgress.done()
      } else {
        // 判断是否已经注册过动态路由，避免重复注册
        if (!isDynamicRoutesRegistered) {
          getRouter = await store.dispatch('user/getInfo')
          // // 后台请求得到的路由数据
          // await store.dispatch('permission/generateRoutes', getRouter)
          saveObjArr('dpagmRouter', getRouter) // 存储路由到localStorage
          // eslint-disable-next-line require-atomic-updates
          isDynamicRoutesRegistered = true
          routerGo(to, next) // // 执行跳转，避免死循环
        } else {
          console.log('next')
          next()
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
function routerGo(to, next) {
  const page404 = { path: '*', redirect: '/404', hidden: true }
  getRouter = filterAsyncRouter(getRouter) // 过滤路由
  getRouter.push(page404)
  for (const item of getRouter) {
    router.options.routes.push(item)
    router.addRoute(item) // 动态添加路由
  }
  // router.options.routes.push(page404)
  // router.addRoutes(getRouter) // 动态添加路由
  next({ ...to, replace: true })
}

function saveObjArr(name, data) {
  // localStorage 存储数组对象的方法
  localStorage.setItem(name, JSON.stringify(data))
}

function getObjArr(name) {
  // localStorage 获取数组对象的方法
  return JSON.parse(window.localStorage.getItem(name))
}
function filterAsyncRouter(asyncRouterMap) {
  // 遍历后台传来的路由字符串，转换为组件对象
  const accessedRouters = asyncRouterMap.filter((route) => {
    if (route.component) {
      if (route.component === 'Layout') {
        // Layout组件特殊处理
        route.component = Layout
      } else {
        route.component = _import(route.component)
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })

  return accessedRouters
}
